package com.itheima.auth.filter;

import com.itheima.service.UserService;
import com.itheima.utils.JwtTokenUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 在权限校验前加一个过滤器，验证前端传来的token是否包含数据库中存在的用户名
 */

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final String TOKEN_HEADER = "Authentication";

    @Resource
    private PasswordEncoder passwordEncoder;

    @Reference
    private UserService userService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(TOKEN_HEADER);
        String authentication1 = request.getParameter("Authentication");
        if(token==null&&authentication1!=null){
            token=authentication1;
        }
        try {
            if(!("null".equals(token)||(token==null)||token.equals(null))){
                //jwt解密，拿到当前登入用户名
                String username = JwtTokenUtil.parseToken(token);

                //这块的查询可以通过redis缓存查
                com.itheima.pojo.User user1 = userService.getByUsername(username);
                List<String> list = userService.findPermissionsByUserId(user1.getId());
                String[] permissions =new String[list.size()];
                list.toArray(permissions);


                //模拟数据库查询
                User user = (User) User.withUsername(username).password(user1.getPwd()).authorities(permissions).build();

                //往下传递身份的具体user
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                //往下传递当前登入后的身份 ThreadLocal
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //过滤器放行
            filterChain.doFilter(request, response);
        }
    }

}
